package com.shop.loan.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shop.loan.mapper.LoanOrderByMybatisMapper;
import com.shop.loan.mapper.UserByMybatisMapper;
import com.shop.loan.model.common.CodeByYingCai;
import com.shop.loan.model.common.ResResultByYingCai;
import com.shop.loan.model.entity.LoanOrderByMybatis;
import com.shop.loan.model.entity.UserByMybatis;
import com.shop.loan.model.vo.YingCaiParamVo;
import com.shop.loan.redis.RedisCache;
import com.shop.loan.redis.RedisLockUtil;
import com.shop.loan.redis.RedisUtil;
import com.shop.loan.rentaldata.RentalDataUtil;
import com.shop.loan.service.AsyncService;
import com.shop.loan.service.YingCaiService;
import com.shop.loan.util.RsaUtil;
import com.shop.loan.util.Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;

@Slf4j
@Service
public class YingCaiServiceImpl implements YingCaiService {

    @Value("${api.yc.channelId}")
    private Long channelId;

    //盈彩公钥
    @Value("${api.yc.publicKey}")
    private String publicKey;

    //平台自己公钥
    @Value("${api.yc.s_public}")
    private String s_public;

    //平台自己私钥
    @Value("${api.yc.s_privateKey}")
    private String s_privateKey;

    @Value("${sys.downloadUrl}")
    private String downloadUrl;

    @Resource
    RentalDataUtil rentalDataUtil;

    @Resource
    LoanOrderByMybatisMapper loanOrderByMybatisMapper;

    @Resource
    AsyncService asyncService;

    @Resource
    RedisUtil redisUtil;

    @Resource
    UserByMybatisMapper userByMybatisMapper;

    @Resource
    RedisLockUtil redisLockUtil;

    @Override
    public String checkUser(YingCaiParamVo yingCaiParamVo) {
        if (!StringUtils.hasLength(yingCaiParamVo.getContent()) || !StringUtils.hasLength(yingCaiParamVo.getSign())) {
            return RsaUtil.encodeParam(JSON.parseObject(JSON.toJSONString(new ResResultByYingCai(CodeByYingCai.param_lack))), publicKey, s_privateKey).toJSONString();
        }
        JSONObject dataJs = new JSONObject();
        dataJs.put("amount", "0");
        dataJs.put("msg", "");
        dataJs.put("code", "");
        dataJs.put("expireTime", System.currentTimeMillis() + "");
        try {
            JSONObject paramJs = RsaUtil.decodeParam(JSON.parseObject(JSON.toJSONString(yingCaiParamVo)), publicKey, s_privateKey);
            String phoneMd5 = paramJs.getString("phoneMd5");
            String idMd5 = paramJs.getString("idMd5");

            if (!StringUtils.hasLength(phoneMd5) || !StringUtils.hasLength(idMd5)) {
                return RsaUtil.encodeParam(JSON.parseObject(JSON.toJSONString(new ResResultByYingCai(CodeByYingCai.param_lack))), publicKey, s_privateKey).toJSONString();
//                return new ResResultByYingCai(CodeByYingCai.param_lack);
            }
            UserByMybatis userByMybatis = userByMybatisMapper.selectMobileIdcardByMd5(phoneMd5, idMd5);
            if (userByMybatis != null && userByMybatis.getId() != null) {
                if (userByMybatis.getChannelId() != null && userByMybatis.getChannelId() != channelId.longValue()) {
                    dataJs.put("code", CodeByYingCai.reject.getCode());
                    dataJs.put("msg", CodeByYingCai.reject.getMsg());
                    return RsaUtil.encodeParam(JSON.parseObject(JSON.toJSONString(new ResResultByYingCai(CodeByYingCai.success, dataJs))), publicKey, s_privateKey).toJSONString();
//                    return new ResResultByYingCai(CodeByYingCai.success, dataJs);
                }
                if (!userByMybatis.getMachineStatus()) {
                    dataJs.put("code", CodeByYingCai.reject.getCode());
                    dataJs.put("msg", CodeByYingCai.reject.getMsg());
                    return RsaUtil.encodeParam(JSON.parseObject(JSON.toJSONString(new ResResultByYingCai(CodeByYingCai.success, dataJs))), publicKey, s_privateKey).toJSONString();
//                    return new ResResultByYingCai(CodeByYingCai.success, dataJs);
                }
                LoanOrderByMybatis loanOrderByMybatis = loanOrderByMybatisMapper.selectOrderByIng(userByMybatis.getId());
                if (loanOrderByMybatis != null && loanOrderByMybatis.getId() != null && !loanOrderByMybatis.getOverdueStatus()) {
                    dataJs.put("code", CodeByYingCai.overdue.getCode());
                    dataJs.put("msg", CodeByYingCai.overdue.getMsg());
                    return RsaUtil.encodeParam(JSON.parseObject(JSON.toJSONString(new ResResultByYingCai(CodeByYingCai.success, dataJs))), publicKey, s_privateKey).toJSONString();
//                    return new ResResultByYingCai(CodeByYingCai.success, dataJs);
                }
                if (loanOrderByMybatis != null && loanOrderByMybatis.getId() != null) {
                    dataJs.put("code", CodeByYingCai.ing_order.getCode());
                    dataJs.put("msg", CodeByYingCai.ing_order.getMsg());
                    return RsaUtil.encodeParam(JSON.parseObject(JSON.toJSONString(new ResResultByYingCai(CodeByYingCai.success, dataJs))), publicKey, s_privateKey).toJSONString();
//                    return new ResResultByYingCai(CodeByYingCai.success, dataJs);
                }
            }
            boolean checkStatus = true;
            JSONObject rdRes = rentalDataUtil.getRdCheckByMd5(phoneMd5, idMd5);
            if (rdRes != null) {
                if (rdRes.getBoolean("overdueStatus") || rdRes.getBoolean("blackStatus") || rdRes.getBoolean("ekaStatus") || rdRes.getBoolean("rejectStatus")) {
                    //命中
                    checkStatus = false;
                }
            }
            if (!checkStatus) {
                dataJs.put("code", CodeByYingCai.black.getCode());
                dataJs.put("msg", CodeByYingCai.black.getMsg());
                return RsaUtil.encodeParam(JSON.parseObject(JSON.toJSONString(new ResResultByYingCai(CodeByYingCai.success, dataJs))), publicKey, s_privateKey).toJSONString();
//                return new ResResultByYingCai(CodeByYingCai.success, dataJs);
            }
            dataJs.put("code", CodeByYingCai.loan.getCode());
            dataJs.put("msg", CodeByYingCai.loan.getMsg());
            dataJs.put("amount", "50000");
            return RsaUtil.encodeParam(JSON.parseObject(JSON.toJSONString(new ResResultByYingCai(CodeByYingCai.success, dataJs))), publicKey, s_privateKey).toJSONString();
//            return new ResResultByYingCai(CodeByYingCai.success, dataJs);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(Util.GetErrorDetails(e));
        }
        return RsaUtil.encodeParam(JSON.parseObject(JSON.toJSONString(new ResResultByYingCai(CodeByYingCai.sign_error))), publicKey, s_privateKey).toJSONString();
//        return new ResResultByYingCai(CodeByYingCai.sign_error);
    }


    @Override
    public String apply(YingCaiParamVo yingCaiParamVo) {
        JSONObject paramJs = null;
        try {
            paramJs = RsaUtil.decodeParam(JSON.parseObject(JSON.toJSONString(yingCaiParamVo)), publicKey, s_privateKey);
            String applyId = paramJs.getString("applyId");

            if (!StringUtils.hasLength(applyId)) {
                return RsaUtil.encodeParam(JSON.parseObject(JSON.toJSONString(new ResResultByYingCai(CodeByYingCai.param_lack))), publicKey, s_privateKey).toJSONString();
//                return new ResResultByYingCai(CodeByYingCai.param_lack);
            }
            asyncService.getYingCaiOrderInfo(applyId);

            JSONObject dataJs = new JSONObject();
            dataJs.put("url", downloadUrl);
            return RsaUtil.encodeParam(JSON.parseObject(JSON.toJSONString(new ResResultByYingCai(CodeByYingCai.success, dataJs))), publicKey, s_privateKey).toJSONString();
//            return new ResResultByYingCai(CodeByYingCai.success, dataJs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RsaUtil.encodeParam(JSON.parseObject(JSON.toJSONString(new ResResultByYingCai(CodeByYingCai.sign_error))), publicKey, s_privateKey).toJSONString();
//        return new ResResultByYingCai(CodeByYingCai.sign_error);
    }

    @Override
    public String getUrl(YingCaiParamVo yingCaiParamVo) {
        JSONObject dataJs = new JSONObject();
        dataJs.put("url", downloadUrl);

        return RsaUtil.encodeParam(JSON.parseObject(JSON.toJSONString(new ResResultByYingCai(CodeByYingCai.success, dataJs))), publicKey, s_privateKey).toJSONString();
//        return new ResResultByYingCai(CodeByYingCai.success, dataJs);
    }

    @Async
    @Override
    public void getOrderInfo() {
        String lockValue = String.valueOf(System.currentTimeMillis());
        String lockKey = RedisCache.yingCaiApplyIdGetLock;
        Jedis jedis = redisUtil.getJedis();
        try {
            if (!redisLockUtil.lock(jedis, lockKey, lockValue)) {
                log.info("【盈彩】 获取订单信息线程正在进行中");
                return;
            }
            boolean run = true;
            while (run) {
                Object applyIdObj = redisUtil.rpop(RedisCache.yingCaiApplyIdQueue);
                if (applyIdObj == null) {
                    return;
                }
                asyncService.getYingCaiOrderInfo(applyIdObj.toString());
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(Util.GetErrorDetails(e));
        } finally {
            if (jedis != null) {
                redisLockUtil.release(jedis, lockKey, lockValue);
                jedis.close();
            }
        }
    }
}
